package com.ruoyi.api.controller;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.workstation.domain.User;
import com.ruoyi.workstation.domain.UserLog;
import com.ruoyi.workstation.service.IUserLogService;
import com.ruoyi.workstation.service.IUserService;
import com.ruoyi.workstation.service.impl.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 工作站日志
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/api/user/log")
public class ApiUserLogController {
    private static final Logger log = LoggerFactory.getLogger(ApiUserLogController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IUserLogService userLogService;

    @Autowired
    private IUserService userService;
    @Autowired
    private TokenService tokenService;

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(HttpServletRequest request, MultipartFile file) throws Exception {
        Long userId = tokenService.getLoginUserId(request);
        User user = userService.selectUserByUserId(userId);
        if (user == null) {
            return new AjaxResult(AjaxResult.Type.USER_NOT_EXIST, "");
        }

        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);

            UserLog userLog = new UserLog();
            userLog.setCreator(userId);
            userLog.setFileName(fileName);
            userLog.setNewFileName(FileUtils.getName(fileName));
            userLog.setOriginalFileName(file.getOriginalFilename());

            userLogService.insertUserLog(userLog);
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

}
